<template>
  <view class="notification-page">
    <view class="header">
      <view class="title">消息通知</view>
      <view v-if="notifications.length > 0" class="read-all" @click="markAllAsRead">
        <text>全部已读</text>
      </view>
    </view>
    
    <view v-if="notifications.length === 0" class="empty-container">
      <image class="empty-image" src="/static/images/empty.png"></image>
      <text class="empty-text">暂无消息通知</text>
    </view>
    
    <scroll-view v-else class="notification-list" scroll-y @scrolltolower="loadMore" refresher-enabled @refresherrefresh="onPullDownRefresh">
      <view 
        v-for="(item, index) in notifications" 
        :key="item.id" 
        class="notification-item"
        :class="{ 'unread': item.isRead === 0 }"
        @click="handleNotificationClick(item)"
      >
        <view class="notification-avatar">
          <image class="avatar" :src="item.fromUserAvatar || '/static/images/default-avatar.png'"></image>
        </view>
        <view class="notification-content">
          <view class="notification-text">{{ item.content }}</view>
          <view class="notification-time">{{ formatTime(item.createTime) }}</view>
        </view>
        <view class="notification-actions">
          <view class="action-btn delete-btn" @click.stop="deleteNotification(item.id, index)">
            <text>删除</text>
          </view>
        </view>
      </view>
      
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <view v-if="!loading && !hasMore" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { notificationApi } from '@/utils/api.js';

export default {
  data() {
    return {
      notifications: [],
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      hasMore: true
    };
  },
  computed: {
    // 是否还有更多数据
    hasMoreData() {
      return this.notifications.length < this.total;
    }
  },
  onLoad() {
    this.getNotifications();
  },
  onPullDownRefresh() {
    this.getNotifications().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    // 获取通知列表
    async getNotifications(loadMore = false) {
      if (this.loading) return;
      
      try {
        this.loading = true;
        
        if (!loadMore) {
          this.page = 1;
          this.notifications = [];
        }
        
        const res = await notificationApi.getNotifications({
          page: this.page,
          size: this.size
        });
        
        if (res.code === 200 && res.data) {
          const { list, total } = res.data;
          
          if (loadMore) {
            this.notifications = [...this.notifications, ...list];
          } else {
            this.notifications = list;
          }
          
          this.total = total;
          this.hasMore = this.notifications.length < total;
        } else {
          uni.showToast({
            title: '获取通知列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取通知列表失败:', error);
        uni.showToast({
          title: '获取通知列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return;
      
      this.page++;
      this.getNotifications(true);
    },
    
    // 标记所有通知为已读
    async markAllAsRead() {
      try {
        const res = await notificationApi.markAllAsRead();
        
        if (res.code === 200) {
          // 更新本地通知状态
          this.notifications.forEach(item => {
            item.isRead = 1;
          });
          
          uni.showToast({
            title: '已全部标为已读',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('标记全部已读失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },
    
    // 删除通知
    async deleteNotification(id, index) {
      try {
        const res = await notificationApi.deleteNotification(id);
        
        if (res.code === 200) {
          // 从列表中移除
          this.notifications.splice(index, 1);
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('删除通知失败:', error);
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    },
    
    // 处理通知点击
    async handleNotificationClick(notification) {
      try {
        // 如果未读，则标记为已读
        if (notification.isRead === 0) {
          const res = await notificationApi.markAsRead(notification.id);
          if (res.code === 200) {
            notification.isRead = 1;
          }
        }
        
        // 根据通知类型处理跳转
        if (notification.type === 'new_work') {
          // 跳转到作品详情页
          uni.navigateTo({
            url: `/pages/detail/detail?id=${notification.resourceId}`
          });
        } else if (notification.type === 'new_album') {
          // 跳转到专辑详情页
          uni.navigateTo({
            url: `/pages/album-detail/album-detail?id=${notification.resourceId}`
          });
        }
      } catch (error) {
        console.error('处理通知点击失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      
      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;
      
      // 一分钟内
      if (diff < 60 * 1000) {
        return '刚刚';
      }
      
      // 一小时内
      if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前';
      }
      
      // 一天内
      if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
      }
      
      // 一周内
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
      }
      
      // 超过一周
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.notification-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background-color: #ffffff;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
    }
    
    .read-all {
      font-size: 28rpx;
      color: #666666;
    }
  }
  
  .empty-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 600rpx;
    
    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
  
  .notification-list {
    height: calc(100vh - 100rpx);
    
    .notification-item {
      display: flex;
      padding: 30rpx;
      background-color: #ffffff;
      border-bottom: 1px solid #f0f0f0;
      
      &.unread {
        background-color: #f0f8ff;
        
        &::before {
          content: '';
          position: absolute;
          left: 20rpx;
          width: 16rpx;
          height: 16rpx;
          background-color: #ff5252;
          border-radius: 50%;
        }
      }
      
      .notification-avatar {
        width: 80rpx;
        height: 80rpx;
        margin-right: 20rpx;
        
        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
        }
      }
      
      .notification-content {
        flex: 1;
        
        .notification-text {
          font-size: 28rpx;
          line-height: 40rpx;
          margin-bottom: 10rpx;
        }
        
        .notification-time {
          font-size: 24rpx;
          color: #999999;
        }
      }
      
      .notification-actions {
        display: flex;
        align-items: center;
        
        .action-btn {
          padding: 10rpx 20rpx;
          font-size: 24rpx;
          border-radius: 30rpx;
          
          &.delete-btn {
            color: #ff5252;
          }
        }
      }
    }
    
    .loading, .no-more {
      text-align: center;
      padding: 30rpx 0;
      font-size: 24rpx;
      color: #999999;
    }
  }
}
</style>
